package com.easylinkin.linkappapi.quality.service.impl;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.service.OSSService;
import com.easylinkin.linkappapi.quality.dto.*;
import com.easylinkin.linkappapi.quality.entity.Problem;
import com.easylinkin.linkappapi.quality.entity.ProblemType;
import com.easylinkin.linkappapi.quality.entity.QualityPosition;
import com.easylinkin.linkappapi.quality.entity.QualityQuestionDealRecord;
import com.easylinkin.linkappapi.quality.entity.vo.QualityQuestionDealRecordVo;
import com.easylinkin.linkappapi.quality.entity.vo.QualityScreenPageVo;
import com.easylinkin.linkappapi.quality.mapper.*;
import com.easylinkin.linkappapi.quality.service.ProblemService;
import com.easylinkin.linkappapi.quality.service.ProblemTypeService;
import com.easylinkin.linkappapi.quality.service.QualityInspectionAccountService;
import com.easylinkin.linkappapi.quality.service.QualityQuestionInfoService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.mapper.LinkappTenantMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author: kan yuanfeng
 * @Date: 2022/8/19 14:41
 * @Description:
 */
@Service
public class QualityInspectionAccountServiceImpl implements QualityInspectionAccountService {
  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;
  @Autowired
  private QualityQuestionInfoMapper questionInfoMapper;
  @Autowired
  private QualityInspectionMapper qualityInspectionMapper;
  @Autowired
  private QualityQuestionCommentMapper qualityQuestionCommentMapper;
  @Autowired
  private QualityQuestionDealRecordMapper questionDealRecordMapper;
  @Autowired
  private LinkappTenantMapper linkappTenantMapper;
  @Autowired
  private OSSService ossService;

  @Resource
  private ProblemTypeService problemTypeService;

  @Resource
  private ProblemTypeMapper problemTypeMapper;

  @Autowired
  private QualityQuestionInfoService qualityQuestionInfoService;

  /**
   * @Description: 查询质量台账列表
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public IPage<QualityQuestionInfoDto> queryListByPage(
      RequestModel<QualityQuestionInfoDto> requestModel) {
    Page page = requestModel.getPage();
    QualityQuestionInfoDto questionInfoDto = requestModel.getCustomQueryParams();
    questionInfoDto.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    IPage<QualityQuestionInfoDto> infoDtoIPage = questionInfoMapper.findAccountList(page,questionInfoDto);
    infoDtoIPage.getRecords().forEach(r ->{
      if (Integer.valueOf(1).equals(r.getType())){
        //设置整改时间，复核时间
        List<QualityQuestionDealRecord> dealRecordList = r.getDealRecordList();
        r.setRectifierTime(setReTime(1,dealRecordList));
        r.setReviewerTime(setReTime(2,dealRecordList));
        //设置是否超期整改 是否超期复核
        r.setRectifiAfter(setAfter(1,r.getRectifiLimitTime(), dealRecordList));
        r.setReviewAfter(setAfter(2,r.getReviewLimitTime(), dealRecordList));
      }
    });
    return infoDtoIPage;
  }

  @Resource
  private ProblemService problemService;

  @Override
  public IPage<QualityQuestionInfoDto> queryOpenApiListByPage(
      RequestModel<QualityQuestionInfoDto> requestModel) {
    Page page = requestModel.getPage();
    QualityQuestionInfoDto questionInfoDto = requestModel.getCustomQueryParams();
    //处理问题信息
    if(StringUtils.isNotBlank(questionInfoDto.getQuestionContent())){
      QueryWrapper<Problem> queryWrapper = new QueryWrapper<>();
      queryWrapper.like("content_",questionInfoDto.getQuestionContent());
      List<Problem> list = problemService.list(queryWrapper);
      List<Integer> problemIds = list.stream().map(Problem::getId).collect(Collectors.toList());
      if(CollectionUtil.isEmpty(problemIds)){
        problemIds.add(0);
      }
      questionInfoDto.setQuestionDescribeIds(problemIds);
    }
    if(StringUtils.isNotBlank(questionInfoDto.getDangerTypeName())){
      QueryWrapper<ProblemType> queryWrapper = new QueryWrapper<>();
      queryWrapper.like("name_",questionInfoDto.getDangerTypeName());
      List<ProblemType> list = problemTypeService.list(queryWrapper);
      List<Integer> dangerTypeIds = list.stream().map(ProblemType::getId).collect(Collectors.toList());
      if(CollectionUtil.isEmpty(dangerTypeIds)){
        dangerTypeIds.add(0);
      }
      questionInfoDto.setProblemTypeIds(dangerTypeIds);
    }
    IPage<QualityQuestionInfoDto> infoDtoIPage = questionInfoMapper.findOpenApiAccountList(page,questionInfoDto);
    infoDtoIPage.getRecords().forEach(r ->{
      if (Integer.valueOf(1).equals(r.getType())){
        //设置整改时间，复核时间
        List<QualityQuestionDealRecord> dealRecordList = r.getDealRecordList();
        r.setRectifierTime(setReTime(1,dealRecordList));
        r.setReviewerTime(setReTime(2,dealRecordList));
        //设置是否超期整改 是否超期复核
        r.setRectifiAfter(setAfter(1,r.getRectifiLimitTime(), dealRecordList));
        r.setReviewAfter(setAfter(2,r.getReviewLimitTime(), dealRecordList));
      }
    });
    return infoDtoIPage;
  }

  @Override
  public JSONObject getOpenApiCount(QualityQuestionInfoDto qualityQuestionInfoDto) {
    //处理参数，开始时间，结束时间，项目id
    JSONObject jsonObject = new JSONObject();
    List<QualityQuestionStatisticsDTO> result =  questionInfoMapper.getOpenApiCount(qualityQuestionInfoDto);
    //避免出现有检查，但没问题的情况，这里查一下所有的检查数据
    List<QualityQuestionStatisticsDTO> checkResult = questionInfoMapper.getOpenApiCheckNumCount(qualityQuestionInfoDto);
    Map<Long, List<QualityQuestionStatisticsDTO>> checkMap = checkResult.stream()
        .collect(Collectors.groupingBy(QualityQuestionStatisticsDTO::getProjectId));
    List<Long> existList = result.stream().map(QualityQuestionStatisticsDTO::getProjectId)
        .collect(Collectors.toList());
    result.forEach(item->{
      //填充检查总数
      QualityQuestionInfoDto questionInfoDto = new QualityQuestionInfoDto();
      questionInfoDto.setTenantId(item.getTenantId());
      questionInfoDto.setQuestionState(5);
      questionInfoDto.setStartTime(qualityQuestionInfoDto.getStartTime());
      questionInfoDto.setEndTime(qualityQuestionInfoDto.getEndTime());
//      Integer i = questionInfoMapper.getCount(questionInfoDto);
//      item.setCheckNum(i);
      item.setCheckNum(0);
      List<QualityQuestionStatisticsDTO> qualityQuestionStatisticsDTOS = checkMap
          .get(item.getProjectId());
      if(CollectionUtil.isNotEmpty(qualityQuestionStatisticsDTOS)){
        item.setCheckNum(qualityQuestionStatisticsDTOS.get(0).getCheckNum());
      }
      item.setInTimeFinishedRatio(0.0);
      item.setFinishedNumRatio(0.0);
      //处理整改率
      if(item.getQuestionTotalNum()!=null && item.getQuestionTotalNum()!=0){
        item.setFinishedNumRatio(item.getQualifiedNum()*1.0/item.getQuestionTotalNum());
      }

      //处理及时整改率
      List<QualityQuestionInfoDto> infoDtos = questionInfoMapper.findList(questionInfoDto);
      infoDtos.forEach(r ->{
        if (Integer.valueOf(1).equals(r.getType())){
          //设置整改时间，复核时间
          List<QualityQuestionDealRecord> dealRecordList = r.getDealRecordList();
          r.setRectifierTime(setReTime(1,dealRecordList));
          r.setReviewerTime(setReTime(2,dealRecordList));
          //设置是否超期整改 是否超期复核
          r.setRectifiAfter(setAfter(1,r.getRectifiLimitTime(), dealRecordList));
          r.setReviewAfter(setAfter(2,r.getReviewLimitTime(), dealRecordList));
        }
      });
      long count = infoDtos.stream().filter(info -> Boolean.FALSE.equals(info.getRectifiAfter())
          && info.getQuestionState()!=null &&info.getQuestionState()!=1)
          .count();

      if(item.getQuestionTotalNum()!=null && item.getQuestionTotalNum()!=0){
        item.setInTimeFinishedRatio((double) count/item.getQuestionTotalNum());
      }
    });
    //将检查信息遍历一下，避免出现有检查没问题单的数据漏掉
    checkMap.keySet().forEach(item->{
      if(!existList.contains(item)){
        QualityQuestionStatisticsDTO qualityQuestionStatisticsDTO = checkMap.get(item).get(0);
        qualityQuestionStatisticsDTO.setInTimeFinishedRatio(0.0);
        qualityQuestionStatisticsDTO.setFinishedNumRatio(0.0);
        qualityQuestionStatisticsDTO.setNotQualityNum(0);
        qualityQuestionStatisticsDTO.setQuestionTotalNum(0);
        qualityQuestionStatisticsDTO.setWaitRectifyNum(0);
        qualityQuestionStatisticsDTO.setWaitBeReviewNum(0);
        qualityQuestionStatisticsDTO.setQualifiedNum(0);
        result.add(qualityQuestionStatisticsDTO);
      }
    });
    //进行排序
    Collections.sort(result, new Comparator<QualityQuestionStatisticsDTO>() {
      @Override
      public int compare(QualityQuestionStatisticsDTO o1, QualityQuestionStatisticsDTO o2) {
        double diff = o2.getFinishedNumRatio() - o1.getFinishedNumRatio();
          if (diff > 0) {
            return 1;
          }else if (diff < 0) {
            return -1;
          }
          return 0;
      }
    });
//    if(qualityQuestionInfoDto.getPage()!=null && qualityQuestionInfoDto.getSize()!=null){
//      result = result.stream().limit(qualityQuestionInfoDto.getSize())
//          .skip((qualityQuestionInfoDto.getPage()-1) * qualityQuestionInfoDto.getSize())
//          .collect(Collectors.toList());
//      jsonObject.put("current",qualityQuestionInfoDto.getPage());
//    }
    jsonObject.put("records",result);
    jsonObject.put("total",result.size());
    return jsonObject;
  }

  /**
   * @Description: 质量台账统计
   * @author kan yuanfeng
   * @date 2023/05/26 11:42
   */
  @Override
  public QualityQuestionStatisticsDTO getStatistics(QualityQuestionInfoDto qualityQuestionInfoDto) {
    RequestModel<QualityQuestionInfoDto> requestModel = new RequestModel<>();
    requestModel.setPage(new Page<>(1,-1));
    requestModel.setCustomQueryParams(qualityQuestionInfoDto);
    IPage<QualityQuestionInfoDto> dtoIPage = this.queryListByPage(requestModel);
    List<QualityQuestionInfoDto> records = dtoIPage.getRecords();
    QualityQuestionStatisticsDTO questionStatisticsDTO = new QualityQuestionStatisticsDTO();
    //总数
    questionStatisticsDTO.setQuestionTotalNum(records.size());
    //待整改
    questionStatisticsDTO.setWaitRectifyNum(getNum(records,1));
    //待复核
    questionStatisticsDTO.setWaitBeReviewNum(getNum(records,2));
    //合格
    questionStatisticsDTO.setQualifiedNum(getNum(records,3));
    //不合格
    questionStatisticsDTO.setNotQualityNum(getNum(records,4));
    //无需整改
    questionStatisticsDTO.setNoRequired(getNum(records,5));

    //计算超期未整改
    int count = (int)records.stream().filter(r ->Boolean.TRUE.equals(r.getRectifiAfter())).count();
    questionStatisticsDTO.setOverdunNum(count);

    List<Long> questionInfoIds = records.stream().filter(r-> Integer.valueOf(1).equals(r.getType())).map(r -> r.getId()).collect(Collectors.toList());
    if (CollectionUtil.isNotEmpty(questionInfoIds)){
      List<String> list = qualityQuestionInfoService.dealRecord(questionInfoIds);
      //及时整改率
      questionStatisticsDTO.setInTimeFinishedRatioStr(list.get(0));
      //整改成功率
      questionStatisticsDTO.setFinishedNumRatioStr(list.get(1));
    }else {
      //及时整改率
      questionStatisticsDTO.setInTimeFinishedRatioStr("0.0%");
      //整改成功率
      questionStatisticsDTO.setFinishedNumRatioStr("0.0%");
    }
    return questionStatisticsDTO;
  }

  /**
   * @Description: 删除质量台账
   * @author kan yuanfeng
   * @date 2023/05/26 11:42
   */
  @Override
  public void delBatch(List<QualityQuestionInfoDto> list) {
    //质量问题
    List<Long> qualityQuestionInfoIds = list.stream().filter(l -> Integer.valueOf(1).equals(l.getType())).map(l -> l.getId()).collect(Collectors.toList());
    if (CollectionUtil.isNotEmpty(qualityQuestionInfoIds)){
      qualityQuestionInfoService.deleteByIds(qualityQuestionInfoIds);
    }
    //质量巡检
    List<Long> qualityInspectionIds = list.stream().filter(l -> Integer.valueOf(2).equals(l.getType())).map(l -> l.getId()).collect(Collectors.toList());
    if (CollectionUtil.isNotEmpty(qualityInspectionIds)){
      qualityInspectionMapper.deleteBatchIds(qualityInspectionIds);
    }
  }

  /**
   * 过滤获取数量
   * @param records
   * @param state
   */
  private int getNum(List<QualityQuestionInfoDto> records, Integer state) {
    int num = (int) records.stream().filter(r->Integer.valueOf(state).equals(r.getQuestionState())).count();
    return num;
  }

  /**
   * @Description: 质量台账详细
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public QualityQuestionInfoDto findById(Integer id, Integer type) {
    QualityQuestionInfoDto qualityQuestionInfoDto = new QualityQuestionInfoDto();
    if (Integer.valueOf(1).equals(type)){
      //问题
      qualityQuestionInfoDto = questionInfoMapper.selectDtoOne((Long.valueOf(id)));
      if (Integer.valueOf(0).equals(qualityQuestionInfoDto.getDeleteState())){
        throw new BusinessException("该数据已被删除");
      }
      //查询处理结果
      List<QualityQuestionDealRecord> dealRecords = questionDealRecordMapper
          .selectDealListByQuestionId(qualityQuestionInfoDto.getId());
      qualityQuestionInfoDto.setDealRecordList(dealRecords);
      //查询评论
      List<QualityQuestionCommentDto> questionComment = qualityQuestionCommentMapper
          .getQuestionComment((Long.valueOf(id)));
      qualityQuestionInfoDto.setCommentList(questionComment);
    }else {
      //巡检记录
      QualityInspectionDTO qualityInspectionDTO = qualityInspectionMapper.findById(id);
      if (null == qualityInspectionDTO){
        throw new BusinessException("该数据已被删除");
      }
      qualityQuestionInfoDto.setImgs(qualityInspectionDTO.getUrl());
      LinkappUser linkappUser = new LinkappUser();
      linkappUser.setNickname(qualityInspectionDTO.getNickname());
      linkappUser.setPhone(qualityInspectionDTO.getPhone());
      qualityQuestionInfoDto.setAppUser(linkappUser);
      qualityQuestionInfoDto.setCreateTime(qualityInspectionDTO.getCreateTime());
      qualityQuestionInfoDto.setMemo(qualityInspectionDTO.getExplain());
      Problem problem = new Problem();
      problem.setFullName(qualityInspectionDTO.getProblemName());
      qualityQuestionInfoDto.setProblem(problem);
      QualityPosition position = new QualityPosition();
      position.setFullName(qualityInspectionDTO.getPositionName());
      qualityQuestionInfoDto.setPosition(position);
      qualityQuestionInfoDto.setQuestionLevel(qualityInspectionDTO.getLevel());
      qualityQuestionInfoDto.setQuestionState(5);
    }
    //问题分类
    Problem problem = qualityQuestionInfoDto.getProblem();
    if (problem != null && StringUtils.isNotBlank(problem.getFullName())){
      String fullName = problem.getFullName();
      problem.setFullName(fullName.substring(0,fullName.lastIndexOf("/")));
      problem.setContent(fullName.substring(fullName.lastIndexOf("/")+1));
    }
    return qualityQuestionInfoDto;
  }

  /**
   * 组织excel数据
   * @param id
   * @return
   */
  @Override
  public Workbook exportById(Integer id, Integer type) {
    // 单sheet或多sheet 只需要更改此处即可
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    LinkappTenant query = new LinkappTenant();
    query.setId(tenantId);
    LinkappTenant linkappTenant = linkappTenantMapper.selectLinkappTenant(query);
    Map<String, Object> map = new HashMap<>();
    QualityQuestionInfoDto questionInfoDto = this.findById(id, type);
    if (StringUtils.isBlank(questionInfoDto.getMemo())){
      questionInfoDto.setMemo(" ");
    }
    if (Integer.valueOf(1).equals(type)){
      //拼接分包单位
      String orgName = questionInfoDto.getSubOrgName();
      String subGroupName = questionInfoDto.getSubGroupName();
      if (StringUtils.isNotBlank(orgName) && StringUtils.isNotBlank(subGroupName)){
        questionInfoDto.setSubOrgName(orgName+"/"+subGroupName);
      }
    }
    //组织问题级别严重等级当前状态
    String questionLevel = "";
    String urgentLevel = "";
    String questionState = "";
    String[] questionLevels = {"","一级","二级","三级","四级"};
    if (null != questionInfoDto.getQuestionLevel()){
      questionLevel = questionLevels[questionInfoDto.getQuestionLevel()];
    }
    String[] urgentLevels = {"","一般","严重","紧要"};
    if (null != questionInfoDto.getUrgentLevel()){
      urgentLevel = urgentLevels[questionInfoDto.getUrgentLevel()];
    }
    String[] questionStates = {"","待整改","待复核","合格","不合格","无需整改"};
    if (null != questionInfoDto.getQuestionState()){
      questionState = questionStates[questionInfoDto.getQuestionState()];
    }
    map.put("questionLevel",questionLevel);
    map.put("urgentLevel",urgentLevel);
    map.put("questionState",questionState);
    map.put("projectName",linkappTenant.getPlatformProjectName());
    String tempName = "QualityAccount.xlsx";
    if (!Integer.valueOf(1).equals(type)){
      tempName = "QualityAccount2.xlsx";
    }else if (null == questionInfoDto.getDealRecordList() || questionInfoDto.getDealRecordList().size() < 1){
      tempName = "QualityAccount1.xlsx";
    }else {
      //组织导出数据
      List<QualityQuestionDealRecordVo> qualityQuestionDealRecordVos = BeanUtil
          .copyToList(questionInfoDto.getDealRecordList(), QualityQuestionDealRecordVo.class);
      qualityQuestionDealRecordVos.forEach(q->{
        if (Integer.valueOf(1).equals(q.getDealType())){
          q.setDealLabel("整改情况");
          q.setDealName("整改人");
          q.setDealTimeLabel("接收时间");
        }else {
          q.setDealLabel("复查意见");
          q.setDealName("复查人");
          q.setDealTimeLabel("复查时间");
          Integer passType = q.getPassType();
          q.setDealMemo(Integer.valueOf(1).equals(passType)?"通过\n":"不通过\n"+q.getDealMemo());
        }
      });
      questionInfoDto.setDealRecordVoList(qualityQuestionDealRecordVos);
    }
    map.put("pojo",questionInfoDto);
    TemplateExportParams params = new TemplateExportParams(new ClassPathResource("templates/"+tempName).getPath(),true);
    params.setColForEach(true);
    //组织图片
    setImage(map,questionInfoDto);
    Workbook workbook = ExcelExportUtil.exportExcel(params, map);
    //合并单元格
    Sheet sheet = workbook.getSheetAt(0);
    CellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setBorderRight(BorderStyle.THIN);
    cellStyle.setBorderTop(BorderStyle.THIN);
    cellStyle.setBorderBottom(BorderStyle.THIN);
    if (null != questionInfoDto.getDealRecordList() && questionInfoDto.getDealRecordList().size() > 0){
      for (int i = 0; i < questionInfoDto.getDealRecordList().size(); i++) {
        if (i >0){
//          sheet.addMergedRegion(new CellRangeAddress(9+(i-1)*2, 10+(i-1)*2, 0, 0));
//          sheet.addMergedRegion(new CellRangeAddress(9+(i-1)*2, 9+(i-1)*2, 1, 11));
//          sheet.addMergedRegion(new CellRangeAddress(10+(i-1)*2, 10+(i-1)*2, 1, 2));
//          sheet.addMergedRegion(new CellRangeAddress(10+(i-1)*2, 10+(i-1)*2, 3, 6));
//          sheet.addMergedRegion(new CellRangeAddress(10+(i-1)*2, 10+(i-1)*2, 7, 8));
//          sheet.addMergedRegion(new CellRangeAddress(10+(i-1)*2, 10+(i-1)*2, 9, 11));
        }
        sheet.getRow(9 + (i - 1) * 2).getCell(11).setCellStyle(cellStyle);
        sheet.getRow(10 + (i - 1) * 2).getCell(11).setCellStyle(cellStyle);
      }
    }
    this.setImageSheet(workbook, (List<ImageDTO>) map.get("img"));
    return workbook;
  }

  /**
   * @Description: 查询数量
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public Map<String, String> getCount(QualityQuestionInfoDto questionInfoDto,String tenantId) {
    Map<String, String> map = new HashMap<>();
    questionInfoDto.setTenantId(tenantId);
    if(StringUtils.isBlank(tenantId)){
      questionInfoDto.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
    //求全部
    questionInfoDto.setQuestionState(null);
    setValueName(questionInfoDto, map,"全部");
    //求待整改
    questionInfoDto.setQuestionState(1);
    setValueName(questionInfoDto, map,"待整改");
    //求待复核
    questionInfoDto.setQuestionState(2);
    setValueName(questionInfoDto, map,"待复核");
    //合格
    questionInfoDto.setQuestionState(3);
    setValueName(questionInfoDto, map,"合格");
    //不合格
    questionInfoDto.setQuestionState(4);
    setValueName(questionInfoDto, map,"不合格");
    //无需整改
    questionInfoDto.setQuestionState(5);
    setValueName(questionInfoDto, map,"无需整改");
    return map;
  }

  @Override
  public RestMessage qualityCheckTrend(QualityScreenPageVo qualityScreenPageVo) {
    Date startTime = qualityScreenPageVo.getStartTime();
    Date endTime = qualityScreenPageVo.getEndTime();
    if(startTime == null && endTime == null){
      endTime = DateUtil.endOfDay(DateUtil.date());
      startTime = DateUtil.beginOfDay(DateUtil.offsetDay(endTime,-6));
    }
    qualityScreenPageVo.setStartTime(startTime);
    qualityScreenPageVo.setEndTime(endTime);
    List<Map<String,Object>> countLs = questionInfoMapper.selectQualityCheckTrend(qualityScreenPageVo);

    Map<String,Integer> mp = new HashMap<>();
    if(CollectionUtil.isNotEmpty(countLs)){
      countLs.stream().forEach(c->{
        String ymd = c.get("create_time").toString();
        Long type = Long.parseLong(c.get("type").toString());;
        Long num = Long.parseLong(c.get("num").toString());;
        mp.put(ymd+ "@" + type, num.intValue());
      });
    }

    //参数补全
    TreeMap<String,Map<Integer,Integer>> finMp = new TreeMap<>();
    while (startTime.before(endTime)){
      String ymd = DateUtil.format(startTime, DatePattern.NORM_DATE_PATTERN);
      String ymdTypeIns = ymd+ "@" + 1;
      String ymdTypeQue = ymd+ "@" + 2;
      Integer insNum = mp.get(ymdTypeIns);
      if(insNum == null){
        insNum = 0;
      }
      Integer queNum = mp.get(ymdTypeQue);
      if(queNum == null) {
        queNum = 0;
      }

      Map<Integer,Integer> typeMp = new HashMap<>();
      typeMp.put(1,insNum);
      typeMp.put(2,queNum);

      finMp.put(ymd.substring(5),typeMp);
      startTime = DateUtil.offsetDay(startTime,1);
    }
    return RestBuilders.successBuilder().data(finMp).build();
  }

  @Override
  public RestMessage countByFirstLevelProblemName(QualityScreenPageVo qualityScreenPageVo) {
    List<Map<String,Object>> mpLs = new ArrayList<>();

    String queryType = qualityScreenPageVo.getQueryType();
    if (StringUtils.isBlank(queryType)) {
      queryType = "7d";
    }
    Date startTime = qualityScreenPageVo.getStartTime();
    Date endTime = qualityScreenPageVo.getEndTime();
    if(startTime == null && endTime == null){
      endTime = DateUtil.endOfDay(DateUtil.date());
    }
    switch(queryType){
      case "30d":
        startTime = DateUtil.beginOfDay(DateUtil.offsetDay(endTime,-29));
        break;
      case "sm":
        startTime = DateUtil.beginOfDay(DateUtil.offsetMonth(endTime,-5));
        break;
      case "7d":
        startTime = DateUtil.beginOfDay(DateUtil.offsetDay(endTime, -6));
        break;
      default:
        break;
    }
    qualityScreenPageVo.setStartTime(startTime);
    qualityScreenPageVo.setEndTime(endTime);
    List<Map<String,Object>> countLs = questionInfoMapper.countByFirstLevelProblemName(qualityScreenPageVo);

    //数据处理
    int otherNum = 0;
    Map<String,Object> otherMp = new HashMap<>();
    otherMp.put("name","其他");
    otherMp.put("num",otherNum);
    if(CollectionUtil.isEmpty(countLs)){
      //需要查询一级分类取前5个
      QueryWrapper<ProblemType> qw = new QueryWrapper<>();
      qw.eq("level_",1);
      qw.isNull("tenant_id_");
      qw.orderByDesc("create_time_");
      List<ProblemType> problemTypeLs = problemTypeMapper.selectList(qw);
      if(CollectionUtil.isNotEmpty(problemTypeLs)){
        int size = problemTypeLs.size();
        if(size > 5){
          size = 5;
        }
        for(int i = 0;i < size;i++){
          ProblemType problemType = problemTypeLs.get(i);
          String name = problemType.getName();
          Map<String, Object> mp = new HashMap<>();
          mp.put("name", name);
          mp.put("num", 0);
          mpLs.add(mp);
        }
        mpLs.add(otherMp);
      }
    }else{
      for(int i = 0;i < countLs.size();i++){
        Map<String,Object> mp = countLs.get(i);
        int num = Integer.parseInt(mp.get("num").toString());
        if(i > 4){
          otherNum += num;
          otherMp.put("num",otherNum);
        }else{
          mpLs.add(mp);
        }
      }
      if(Integer.parseInt(otherMp.get("num").toString())>0) {
        mpLs.add(otherMp);
      }
    }
    return RestBuilders.successBuilder().data(mpLs).build();
  }

  /**
   * 质量检查分析-问题分类统计
   */
  @Override
  public RestMessage queClassStatis(QuestionClassQueryDTO dto) {
    List<QuestionClassDTO> questionClassDTOS = questionInfoMapper.queClassStatis(dto);
    return RestBuilders.successBuilder().data(questionClassDTOS).build();
  }

  /**
   * 质量检查分析-各项目问题出现分析
   * @param dto
   * @return
   */
  @Override
  public RestMessage projectQuestionStatis(QuestionClassQueryDTO dto) {
    List<ProjectQuestionDTO> projectQuestionDTOS = questionInfoMapper.projectQuestionStatis(dto);
    return RestBuilders.successBuilder().data(projectQuestionDTOS).build();
  }


  /**
   * 设置名称
   * @param questionInfoDto
   * @param map
   */
  private void setValueName(QualityQuestionInfoDto questionInfoDto, Map<String, String> map,String name) {
    Integer i = questionInfoMapper.getCount(questionInfoDto);
    map.put(questionInfoDto.getQuestionState()+"",name+"("+i+")");
  }

  /**
   * 组织图片实体
   * @param map
   * @param questionInfoDto
   */
  private void setImage(Map<String, Object> map, QualityQuestionInfoDto questionInfoDto) {
    List<ImageDTO> imageDTOS = new ArrayList<>();
    ImageDTO imageDTO = new ImageDTO();
    imageDTO.setName("检查记录照片");
    imageDTO.setTime(questionInfoDto.getCreateTime());
    String imgs = questionInfoDto.getImgs();
    if (StringUtils.isNotBlank(imgs)){
      List<ImageEntity> images = new ArrayList<>();
      String[] split = imgs.split(",");
      for (int i = 0; i < split.length; i++) {
        ImageEntity image = new ImageEntity();
        image.setUrl(split[i]);
        images.add(image);
      }
      imageDTO.setImages(images);
    }
    imageDTOS.add(imageDTO);
    List<QualityQuestionDealRecord> dealRecordList = questionInfoDto.getDealRecordList();
    if (null != dealRecordList && dealRecordList.size() > 0){
      dealRecordList.forEach(d ->{
        ImageDTO imageDTO1 = new ImageDTO();
        imageDTO1.setName(Integer.valueOf(1).equals(d.getDealType())?"整改照片":"复核照片");
        imageDTO1.setTime(d.getCreateTime());
        String dDealImgs = d.getDealImgs();
        if (StringUtils.isNotBlank(dDealImgs)){
          List<ImageEntity> images = new ArrayList<>();
          String[] split = dDealImgs.split(",");
          for (int i = 0; i < split.length; i++) {
            ImageEntity image = new ImageEntity();
            image.setUrl(split[i]);
            images.add(image);
          }
          imageDTO1.setImages(images);
        }
        imageDTOS.add(imageDTO1);
      });
    }
    map.put("img",imageDTOS);
  }

  private Boolean setAfter(Integer dealType,Date time, List<QualityQuestionDealRecord> dealRecordList) {
    List<QualityQuestionDealRecord> records = dealRecordList.stream()
        .filter(d -> Integer.valueOf(dealType).equals(d.getDealType()))
        .sorted(Comparator.comparing(QualityQuestionDealRecord::getDealTime))
        .collect(Collectors.toList());
    //与当前时间对比
    if (null != time && time.getTime()<System.currentTimeMillis()){
      if (records.size() > 0 && records.get(0).getDealTime().getTime() <= time.getTime()){
        return false;
      }else {
        return true;
      }
    }else {
      return false;
    }
  }

  /**
   * 设置整改复核时间
   * @param dealType
   * @param dealRecordList
   */
  private Date setReTime(Integer dealType,List<QualityQuestionDealRecord> dealRecordList) {
    Date date = null;
    List<QualityQuestionDealRecord> records = dealRecordList.stream()
        .filter(d -> Integer.valueOf(dealType).equals(d.getDealType()))
        .sorted(Comparator.comparing(QualityQuestionDealRecord::getDealTime).reversed())
        .collect(Collectors.toList());
    if (records.size()>0){
      date = records.get(0).getDealTime();
    }
    return date;
  }

  /**
   * 设置图片sheet
   */
  private void setImageSheet(Workbook workbook,List<ImageDTO> imageDTOS){
    Sheet sheet = workbook.getSheetAt(1);
    Drawing<?> patriarch = sheet.createDrawingPatriarch();
    CellStyle style = workbook.createCellStyle();
    style.setAlignment(HorizontalAlignment.CENTER);//(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.CENTER);//(VerticalAlignment.CENTER);

    AtomicInteger rNum = new AtomicInteger();
    imageDTOS.forEach(image -> {
      if (rNum.get() ==0){
        sheet.getRow(0).getCell(6).setCellValue(image.getTime());
      }else {
        int lastRowNum = sheet.getLastRowNum();
        Row row= sheet.createRow(lastRowNum + 1);
        row.setHeightInPoints(40);//设置行高
        //合并单元格
        row.createCell(0).setCellValue(image.getName());
        row.createCell(6).setCellValue(image.getTime());
        for (int i = 0; i < 6; i++) {
          if (i>0){
            row.createCell(i);
          }
          row.getCell(i).setCellStyle(sheet.getRow(0).getCell(0).getCellStyle());
        }
        row.getCell(6).setCellStyle(sheet.getRow(0).getCell(6).getCellStyle());
        sheet.addMergedRegion(new CellRangeAddress(lastRowNum + 1, lastRowNum + 1, 0, 5));
      }
      rNum.getAndIncrement();
      XSSFClientAnchor anchor;
      int rowNum = sheet.getLastRowNum();
      Row imgRow = sheet.createRow(rowNum + 1);
      if (null != image.getImages() && image.getImages().size() > 0){
        for(int i=0;i<image.getImages().size();i++) {
          String url = image.getImages().get(0).getUrl();
          imgRow.setHeightInPoints(150);
          Cell cell = imgRow.createCell(i);
          /**
           * 该构造函数有8个参数
           * 前四个参数是控制图片在单元格的位置，分别是图片距离单元格left，top，right，bottom的像素距离
           * 后四个参数，前两个表示图片左上角所在的cellNum和 rowNum，后两个参数对应的表示图片右下角所在的cellNum和 rowNum，
           * excel中的cellNum和rowNum的index都是从0开始的
           */
          anchor = new XSSFClientAnchor(0, 0,
              sheet.getColumnWidth( cell.getColumnIndex() + i) * 1000,
              cell.getRow().getHeight() * 1000,
              cell.getColumnIndex() + i, cell.getRowIndex(),
              cell.getColumnIndex() + i+1, cell.getRowIndex());
          anchor.setAnchorType(AnchorType.byId(3));
          try {
            URL urlObj = new URL(url);
            BufferedImage bufferImg = ImageIO.read(urlObj);
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            ImageIO.write(bufferImg, "png", byteArrayOut);
            patriarch.createPicture(anchor,workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
            byteArrayOut.close();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }

    });
  }
}
